<template>
  <a-card :bordered="false">
    <a-spin :spinning="isLoading">
      <div class="card-title">{{ $route.meta.title }}</div>

      <div class="table-operator">
        <!-- 搜索板块 -->
        <a-row class="row-item-search">
          <a-form class="search-form" layout="inline" @submit="handleSearch">
            <a-form-item label="搜索条件">
              <a-checkbox v-model:checked="g_name">相同用户名</a-checkbox>
              <a-checkbox v-model:checked="g_tel">相同电话</a-checkbox>
              <a-checkbox v-model:checked="g_address">相同地址</a-checkbox>
            </a-form-item>
            <a-form-item class="search-btn">
              <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
            </a-form-item>
            <a-form-item class="search-btn">
              <a-button @click="handleReset">重置</a-button>
            </a-form-item>
          </a-form>
        </a-row>
      </div>
      <div class="ant-table ant-table-scroll-position-left ant-table-default ant-table-bordered">
        <div class="ant-table-content">
          <div class="ant-table-body">
            <div class="ant-table-bnt" v-if="false">
              <a-button @click="handleMerge">合并订单</a-button>
            </div>
            <table>
              <thead class="ant-table-thead">
                <tr>
                  <th style="width: 50px;"><a-checkbox v-if="false" v-model:checked="checkAll" @change="onCheckAllChange"></a-checkbox></th>
                  <template v-for="(item, index) in columns">
                    <th :style="`text-align:${item.align};width:${item.width}`">
                      <div class="ant-table-header-column">
                        <span class="ant-table-column-title">{{ item.title }}</span>
                      </div>
                    </th>
                  </template>
                </tr>
              </thead>
              <tbody class="ant-table-tbody">
                <template v-for="(item, index) in mergeOrderList">
                  <template v-for="(orderItm, orderIdx) in item.orderList">
                    <tr class="order-empty">
                      <td colspan="6"></td>
                    </tr>
                    <tr>
                      <td colspan="6">
                        <div class="tabOrdeno">
                          <div class="tabOrdeno_l">
                            <a-checkbox v-if="false" class="tabCheBox" v-model:checked="orderItm.checked" :name="`${index}_${orderIdx}`" @change="onCheckChange">
                            </a-checkbox>
                            <span class="mr-20">订单号：{{ orderItm.order_no }}</span>
                          </div>
                        </div>
                      </td>
                    </tr>
                    <tr v-for="(goodsItm, goodsIdx) in orderItm.goods">
                      <td colspan="2">
                        <GoodsItem :data="{
                          image: goodsItm.goods_image,
                          imageAlt: '商品图片',
                          title: goodsItm.goods_name,
                          goodsProps: goodsItm.goods_props,
                          remark: orderItm.merchant_remark
                        }" />
                      </td>
                      <td>
                        {{ orderItm.name }}
                      </td>
                      <td>
                        {{ orderItm.phone }}
                      </td>
                      <td>
                        {{ orderItm.detail }}
                      </td>
                      <td>
                        <div class="actions">
                          <router-link v-if="$auth('/order/detail')"  :to="{ path: '/order/detail', query: { orderId: orderItm.order_id } }">详情</router-link>
                          <a v-action:delete @click="handleRemark(orderItm)">备注</a>

                          <a v-action:deliver v-if="(
                            orderItm.pay_status == PayStatusEnum.SUCCESS.value
                            && orderItm.delivery_type == DeliveryTypeEnum.EXPRESS.value
                            && orderItm.delivery_status == DeliveryStatusEnum.NOT_DELIVERED.value
                            && !inArray(orderItm.order_status, [OrderStatusEnum.CANCELLED.value, OrderStatusEnum.APPLY_CANCEL.value])
                          )" @click="handleDelivery(orderItm)">发货</a>

                          <a v-action:deliver v-if="orderItm.pay_status == PayStatusEnum.SUCCESS.value && orderItm.pay_status != OrderStatusEnum.APPLY_CANCEL.value && !orderItm.express_no" @click="getCreate(index,orderItm.order_id)">运单申请</a>
                          <a v-action:deliver v-if="orderItm.express_no" @click="getLogistics(orderItm.express_no)">物流查询</a>


                        </div>
                      </td>
                    </tr>
                  </template>
                </template>
              </tbody>
            </table>
          </div>
          <!-- 空状态 -->
          <a-empty v-if="!mergeOrderList.length" :image="simpleImage" />
        </div>
      </div>
      <!-- 分页器 -->
      <div v-if="mergeOrderList.length" class="pagination">
        <a-pagination :current="page" :pageSize="per_page" :total="total" @change="onChangePage" />
      </div>


      <DeliveryForm ref="DeliveryForm" @handleSubmit="handleRefresh" />
      <MerchantRemark ref="MerchantRemark" @handleSubmit="handleRefresh" />
    </a-spin>
  </a-card>
</template>

<script>
import { Empty } from 'ant-design-vue'
import { inArray, assignment } from '@/utils/util'
import * as Api from '@/api/order'
import { GoodsItem } from '@/components/Table'
import { DeliveryForm, MerchantRemark } from '@/views/order/modules'

import {
  DeliveryStatusEnum,
  DeliveryTypeEnum,
  OrderSourceEnum,
  OrderStatusEnum,
  PayStatusEnum,
  PayTypeEnum,
  ReceiptStatusEnum
} from '@/common/enum/order'
import * as EventApi from '@/api/order/event'

// 表格字段
const columns = [
  {
    title: '商品信息',
    align: 'left',
    dataIndex: 'goods',
    width: '200px',
    scopedSlots: { customRender: 'goods' }
  },
  {
    title: '买家',
    align: 'center',
    dataIndex: 'user',
    width: '120px',
    scopedSlots: { customRender: 'user' }
  },
  {
    title: '手机号',
    align: 'center',
    dataIndex: 'tel',
    width: '180px',
    scopedSlots: { customRender: 'tel' }
  },
  {
    title: '地址',
    align: 'center',
    dataIndex: 'address',
    width: '280px',
    scopedSlots: { customRender: 'address' }
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    width: '180px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Index',
  components: {
    DeliveryForm,
    GoodsItem,
    MerchantRemark

  },

  data() {
    return {
      // 正在加载
      isLoading: false,
      // 表格字段
      columns,
      // 当前页码
      page: 1,
      // 相同用户名
      g_name: false,
      // 相同电话
      g_tel: false,
      // 相同地址
      g_address: false,
      // 列表数据
      mergeOrderList: [],
      orderlistLength: 0,
      total: 0,
      per_page: 10,

      checkAll: false,
      checkedList: [],

    }
  },
  beforeCreate() {
    // 批量给当前实例赋值
    assignment(this, {
      inArray,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      DeliveryStatusEnum,
      DeliveryTypeEnum,
      OrderSourceEnum,
      OrderStatusEnum,
      PayStatusEnum,
      PayTypeEnum,
      ReceiptStatusEnum
    })
  },
  created() {
    // 初始化页面
    this.init()
  },
  watch: {
    // 监听路由变化
    $route() {
      this.init()
    },
    'checkedList'(val) {
      this.checkAll = this.orderlistLength != 0 && val.length === this.orderlistLength;
    }
  },
  methods: {

    onCheckAllChange(e) {
      this.checkedList = [];
      for (const val of this.mergeOrderList) {
        for (const item of val.orderList) {
          if (e.target.checked) {
            item.checked = true;
            this.checkedList.push(item.order_id);
          } else {
            item.checked = false;
          }
        }
      }
    },

    onCheckChange(e) {
      const i = e.target.name.split('_');
      const checked = e.target.checked;
      this.mergeOrderList[i[0]].orderList[i[1]].checked = checked;
      const order_id = this.mergeOrderList[i[0]].orderList[i[1]].order_id;
      if (checked) {
        this.checkedList.push(order_id);
      } else {
        this.checkedList = this.checkedList.filter(item => item != order_id);
      }
      this.$forceUpdate()
    },



    // 初始化页面
    init() {
      this.handleRefresh(true)
    },


    // 获取列表数据
    getList() {
      this.isLoading = true
      this.orderlistLength = 0
      return Api.getPreCombOrder({ g_name: this.g_name ? 1 : 0, g_tel: this.g_tel ? 1 : 0, g_address: this.g_address ? 1 : 0, page: this.page })
        .then(response => {
          this.mergeOrderList = response.data.data
          this.total = response.data.total
          this.per_page = response.data.per_page
          for (const val of this.mergeOrderList) {
            for (const item of val.orderList) {
              item.checked = false
              this.orderlistLength++
            }
          }
        })
        .finally(() => {
          this.isLoading = false
        })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      bool && (this.page = 1)
      this.checkedList = []
      this.getList()
    },

    // 确认搜索
    handleSearch(e) {
      this.handleRefresh(true)
    },

    // 重置搜索表单
    handleReset() {
      this.g_name = false
      this.g_tel = false
      this.g_address = false
      this.handleRefresh(true)
    },


    // 合并订单
    handleMerge() {
      const { checkedList } = this
      if (checkedList.length <= 1) {
        this.$message.error('至少勾选2个订单', 2.5)
        return;
      }

      this.isLoading = true
      const orderIds = checkedList
      Api.setCombination({ orderIds })
        .then((result) => {
          // 显示成功
          console.log(result)
          this.$message.success(result.message, 1.5)
          this.handleRefresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },

    // 翻页事件
    onChangePage(current) {
      this.page = current
      this.handleRefresh()
    },

    handleRemark(record) {
      this.$refs.MerchantRemark.show(record)
    },

    handleDelivery(record) {
      this.$refs.DeliveryForm.show(record)
    },
    //运单申请
    getCreate(index,orderId){
      this.isLoading = true
      Api.getCreate({ orderId })
        .then(response => {
          if(response.data.trackingNumber){
            this.handleRefresh();
          }
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    //物流查询
    getLogistics(express_no){
      window.open(`https://www.sf-express.com/chn/sc/waybill/waybill-detail/${express_no}`,"_blank")
    },
    // 删除记录
    handleDelete(item) {
      const app = this
      const modal = app.$confirm({
        title: '您确定要删除该订单记录吗?',
        content: '删除后不可恢复，请谨慎操作',
        onOk() {
          return EventApi.deleted(item.order_id)
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

  }
}
</script>

<style lang="less" scoped>
// 分页器
.pagination {
  margin-top: 16px;

  .ant-pagination {
    float: right;
  }
}

.ant-table {
  table {
    // table-layout: fixed;
    border: none;
    border-collapse: collapse;
  }

  .ant-table-bnt {
    margin-bottom: 10px;
    display: -webkit-inline-box;
    display: -ms-inline-flexbox;
    display: inline-flex;
    justify-content: flex-end;
    width: 100%;

    button {
      margin-left: 10px;
    }

  }

  .ant-table-thead>tr {
    border: 1px solid #e8e8e8;
  }

  tr.order-empty {
    height: 15px;
    border: 1px solid #fff;

    td {
      padding: 0;
      border-right: none;
      border-left: none;
      background: none !important;
    }
  }
}

.ant-table-thead>tr>th {
  border-right: none;
  border-bottom: none;
  padding: 12px 12px;
  font-weight: bold;
}

.ant-table-tbody>tr>td {
  border-right: 1px solid #e8e8e8;
  border-left: 1px solid #e8e8e8;
  padding: 12px 12px;
  // text-align: center;
}

.tabCheBox {
  margin-right: 10px;
}

.tabOrdeno {
  display: flex;
  justify-content: space-between;

  .tabOrdeno_l {
    display: flex;
    align-items: center;
  }

  .tabOrdeno_r {
    font-weight: bold;
  }
}

.actions {
  & > a {
    margin-right: 8px;
  }
}
</style>
